package com.qianbei.common.utilis.img;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.widget.Toast;

import com.qianbei.R;
import com.qianbei.common.base.BaseApplication;
import com.qianbei.common.utilis.DateUtil;

import java.io.File;
import java.io.IOException;
public class CanmlTools {

	private int flagCrop; // 0:不剪切 1：系统剪切 2 ：自定义剪切
	/** 请求相机功能 --系统剪切 */
	private static final int CAMERA_DEFAULT_CROP = 1;
	/** 请求相机功能 --自定义剪切 */
	private static final int CAMERA_MY_CROP = 11;
	/** 请求相机功能 --不剪切 */
	private static final int CAMERA_NOCROP = 2;
	/** 请求相机功能 --剪切--成功 */
	private static final int CAMERA_CROP_SUCCESS = 3;

	/** 请求相册 --剪切 */
	private static final int PHOTO_DEFAULT_CROP = 4;
	private static final int PHOTO_MY_CROP = 41;
	private static final int PHOTO_MY_CROP_SUCCE = 42;
	/** 请求相册 --不剪切 */
	private static final int PHOTO_NOCROP = 5;

	/** 调用相机用的Uri */
	private static Uri cameraImageUri = null;
	/** 调用相册用Uri */
	private static Uri imageUri = null;
	/** 记录 点击过来的id */
	private int onClickViewid;

	private Context mContext;

	private CamerCallback mIUpdateUi = null;

	public static final class AppConfig {
		static String appName = "meimi";
		public static String APPFILEPASS = Environment
				.getExternalStorageDirectory() + "/" + appName;
		// public static final String APPIMAGEFILEPASS =APPFILEPASS+"/"+"image";
		static {

			File file = new File(APPFILEPASS);
			if (!file.exists()) {
				file.mkdir();
				file = new File(APPFILEPASS);
				try {
					file.createNewFile();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		/** sd卡是否存在 */
		public static final boolean isSdcardExists = Environment
				.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
		/** 软件名 */
		/** sdcard根目录 */
		// public static final String DIR_PATH = Environment
		// .getExternalStorageDirectory() + "/" + appName;// 不支持多卷标
	}

	public CanmlTools(Context mContext, CamerCallback mIUpdateUi) {
		this.mContext = mContext;
		this.mIUpdateUi = mIUpdateUi;
	}

	/**
	 * 弹出相册和拍照的对话框 isCrop 是否剪切的标志
	 */
	public void showCanmel(int imageid, final int flagCrop) {
		onClickViewid = imageid;
		Dialog dialog = new AlertDialog.Builder(mContext)
//				.setTitle("请选择")
				.setItems(R.array.select_dialog_items,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								switch (which) {
								case 0:
									getCamerImage(flagCrop);
									break;
								case 1:
									getPhoto(flagCrop);
									break;
								default:
									break;
								}
							}
						}).create();
		dialog.show();
	}

	public void showCanmelNodialog(int imageid, final int flagCrop) {
		onClickViewid = imageid;
		getCamerImage(flagCrop);
	}

	// public void showCanmel2(int imageid, final boolean isCorp) {
	// onClickViewid = imageid;
	// Dialog dialog = new AlertDialog.Builder(mContext)
	// .setTitle("请选择")
	// .setItems(R.array.select_dialog_items2,
	// new DialogInterface.OnClickListener() {
	// public void onClick(DialogInterface dialog,
	// int which) {
	// switch (which) {
	// case 0:
	// getCamerImage(isCorp);
	// break;
	// case 1:
	// getPhoto(isCorp);
	// break;
	// case 2:
	// SharepreferenceFile.savePercenterImage("");
	// break;
	// default:
	// break;
	// }
	// }
	// }).create();
	// dialog.show();
	// }

	/**
	 * 拍照 获得图片
	 * 
	 * @param flagCrop 拍照完成是否剪切
	 *
	 * 
	 */
	private void getCamerImage(int flagCrop) {
		if (cameraImageUri != null) {
			cameraImageUri = null;
		}
		cameraImageUri = getImageUri();
		if (cameraImageUri != null) {
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraImageUri);
			int requestCode = CAMERA_NOCROP;
			switch (flagCrop) {
			case 0:
				requestCode = CAMERA_NOCROP;
				break;
			case 1:
				requestCode = CAMERA_DEFAULT_CROP;

				break;
			case 2:
				requestCode = CAMERA_MY_CROP;
				break;
			default:
				break;
			}
			((Activity) mContext).startActivityForResult(intent, requestCode);
		} else {
			Toast.makeText(mContext, "请出入内存卡", Toast.LENGTH_LONG).show();
		}
	}

	/**
	 * 获取相册的内容
	 * 
	 * @param flagCrop  是否剪切
	 *
	 */
	private void getPhoto(int flagCrop) {

		switch (flagCrop) {
		case 0:
			getPhotoNOCrop();
			break;
		case 1:
			getPhotoPickIntent();
			break;
		case 2:
			getPhotoMYCrop();
			break;
		default:
			break;
		}

	}

	/**
	 * 调用相册 后剪切 TODO
	 */
	public void getPhotoPickIntent() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
		intent.setType("image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 480);
		intent.putExtra("outputY", 480);
		intent.putExtra("scale", true);
		intent.putExtra("return-data", false);
		imageUri = getImageUri();
		intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
		intent.putExtra("noFaceDetection", true);
		((Activity) mContext)
				.startActivityForResult(intent, PHOTO_DEFAULT_CROP);

		// Intent intent = new Intent

	}

	/**
	 * 调用相册 后不剪切
	 */
	public void getPhotoNOCrop() {

		Intent intent = new Intent(Intent.ACTION_PICK,
				android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		((Activity) mContext).startActivityForResult(intent, PHOTO_NOCROP);
	}

	/**
	 * 调用相册 自定义剪切
	 */
	public void getPhotoMYCrop() {
		Intent intent = new Intent(Intent.ACTION_PICK,
				android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		((Activity) mContext).startActivityForResult(intent, PHOTO_MY_CROP);
	}

	// 调用相机拍照 后调用自定义剪切
	private void myCrop(Uri uri, int requestCode) {
		Intent intent = new Intent(mContext, ClipPictureActivity.class);
		intent.putExtra("data", uri.getPath());
		((Activity) mContext).startActivityForResult(intent, requestCode);
	}

	// 调用相机拍照截图
	private void cropImageUri(Uri uri, int outputX, int outputY, int requestCode) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", outputX);
		intent.putExtra("outputY", outputY);
		intent.putExtra("scale", true);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
		intent.putExtra("return-data", false);
		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
		intent.putExtra("noFaceDetection", true); // no face detection
		((Activity) mContext).startActivityForResult(intent, requestCode);
	}

	/**
	 * 调用相册 后不剪切
	 */
	public void getPhotoPick() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		intent.setType("image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 80);
		intent.putExtra("outputY", 80);
		intent.putExtra("return-data", true);
	}

	public void onresult(int requestCode, Intent data) {
		switch (requestCode) {
		/** 照相系统剪切成功 */
		case CAMERA_MY_CROP:
			if (cameraImageUri != null) {
				myCrop(cameraImageUri, CAMERA_CROP_SUCCESS);
			} else {
				Toast.makeText(mContext, "请出入内存卡2", Toast.LENGTH_LONG).show();
			}
			break;

		/** 照相系统剪切成功 */
		case CAMERA_DEFAULT_CROP:
			if (cameraImageUri != null) {
				cropImageUri(cameraImageUri, 480, 480, CAMERA_CROP_SUCCESS);
			} else {
				Toast.makeText(mContext, "请出入内存卡2", Toast.LENGTH_LONG).show();
			}
			break;
		/** 照相成功--剪切成功 */
		case CAMERA_CROP_SUCCESS:
			String path1 = null;
			if (data != null) {
				path1 = data.getStringExtra("imgUri");
				mIUpdateUi.camerPickphoto(path1, onClickViewid);
			}
			break;
		/** 照相 ---不剪切的返回 */
		case CAMERA_NOCROP:
			if (cameraImageUri != null) {
				String path2 = cameraImageUri.getPath();
				if (path2 != null) {
					mIUpdateUi.camerPickphoto(path2, onClickViewid);
				}
			}

			break;
		/** 相册---剪切成功 */
		case PHOTO_DEFAULT_CROP:
			String path3 = imageUri.getPath();
			mIUpdateUi.camerPickphoto(path3, onClickViewid);
			/** 相册------不剪切 */
			break;
		case PHOTO_NOCROP:
			String path4 = null;
			String[] proj = { MediaStore.Images.Media.DATA };
			Uri originalUri = data.getData();
			Cursor cursor = ((Activity) mContext).managedQuery(originalUri,
					proj, null, null, null);
			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			if (cursor.moveToFirst()){
				path4 = cursor.getString(column_index);
			}

			mIUpdateUi.camerPickphoto(path4, onClickViewid);
			break;
		/** 调用相册 自定义剪切 */
		case PHOTO_MY_CROP:
			String path5 = null;
			String[] pro = { MediaStore.Images.Media.DATA };
			Uri originalUr = data.getData();
			Cursor cursor1 = ((Activity) mContext).managedQuery(originalUr,
					pro, null, null, null);
			if(cursor1 != null){
				int column_inde = cursor1
						.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				if (cursor1.moveToFirst()){
					path5 = cursor1.getString(column_inde);
				}
			}else{
				path5 = getPath(mContext, originalUr);
			}
			
			Intent intent = new Intent(mContext, ClipPictureActivity.class);
			intent.putExtra("data", path5);
			((Activity) mContext).startActivityForResult(intent,
					PHOTO_MY_CROP_SUCCE);
			break;

		case PHOTO_MY_CROP_SUCCE:
			String path6 = null;
			if (data != null) {
				path6 = data.getStringExtra("imgUri");
				mIUpdateUi.camerPickphoto(path6, onClickViewid);
			}

			// String path3 = myCropImageUri.getPath();

			break;
		}
	}

	/**
	 * 得到拍照的uri
	 * 
	 * @return
	 */
	public static Uri getImageUri() {
		File cache = getCacheDirectory(BaseApplication.mApplication);
		File imgFile = new File(cache, DateUtil.getStringNow() + ".jpg");
		return Uri.fromFile(imgFile);
	}

	public interface CamerCallback {
		// 调用 剪切成功后的操作
		public void camerPickphoto(String imageUri, int i);
	}

	public static File getCacheDirectory(Context context) {
		File appCacheDir = null;
		if (Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			appCacheDir = getExternalCacheDir(context);
		}
		if (appCacheDir == null) {
			appCacheDir = context.getCacheDir();
		}
		return appCacheDir;
	}

	private static File getExternalCacheDir(Context context) {
		File dataDir = new File(new File(
				Environment.getExternalStorageDirectory(), "Android"), "data");
		File appCacheDir = new File(
				new File(dataDir, context.getPackageName()), "cache");
		if (!appCacheDir.exists()) {
			try {
				new File(dataDir, ".nomedia").createNewFile();
			} catch (IOException e) {
			}
			if (!appCacheDir.mkdirs()) {
				return null;
			}
		}
		return appCacheDir;
	}
	
	/** 
	 * <br>功能简述:4.4及以上获取图片的方法
	 * <br>功能详细描述:
	 * <br>注意:
	 * @param context
	 * @param uri
	 * @return
	 */
	@TargetApi(19)
	@SuppressLint("NewApi")
	public static String getPath(final Context context, final Uri uri) {

		final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

		// DocumentProvider
		if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
			// ExternalStorageProvider
			if (isExternalStorageDocument(uri)) {
				final String docId = DocumentsContract.getDocumentId(uri);
				final String[] split = docId.split(":");
				final String type = split[0];

				if ("primary".equalsIgnoreCase(type)) {
					return Environment.getExternalStorageDirectory() + "/" + split[1];
				}
			}
			// DownloadsProvider
			else if (isDownloadsDocument(uri)) {

				final String id = DocumentsContract.getDocumentId(uri);
				final Uri contentUri = ContentUris.withAppendedId(
						Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

				return getDataColumn(context, contentUri, null, null);
			}
			// MediaProvider
			else if (isMediaDocument(uri)) {
				final String docId = DocumentsContract.getDocumentId(uri);
				final String[] split = docId.split(":");
				final String type = split[0];

				Uri contentUri = null;
				if ("image".equals(type)) {
					contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				} else if ("video".equals(type)) {
					contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
				} else if ("audio".equals(type)) {
					contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
				}

				final String selection = "_id=?";
				final String[] selectionArgs = new String[] { split[1] };

				return getDataColumn(context, contentUri, selection, selectionArgs);
			}
		}
		// MediaStore (and general)
		else if ("content".equalsIgnoreCase(uri.getScheme())) {

			// Return the remote address
			if (isGooglePhotosUri(uri))
				return uri.getLastPathSegment();

			return getDataColumn(context, uri, null, null);
		}
		// File
		else if ("file".equalsIgnoreCase(uri.getScheme())) {
			return uri.getPath();
		}

		return null;
	}

	public static String getDataColumn(Context context, Uri uri, String selection,
			String[] selectionArgs) {

		Cursor cursor = null;
		final String column = "_data";
		final String[] projection = { column };

		try {
			cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
					null);
			if (cursor != null && cursor.moveToFirst()) {
				final int index = cursor.getColumnIndexOrThrow(column);
				return cursor.getString(index);
			}
		} finally {
			if (cursor != null)
				cursor.close();
		}
		return null;
	}
	
	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is ExternalStorageProvider.
	 */
	public static boolean isExternalStorageDocument(Uri uri) {
		return "com.android.externalstorage.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is DownloadsProvider.
	 */
	public static boolean isDownloadsDocument(Uri uri) {
		return "com.android.providers.downloads.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is MediaProvider.
	 */
	public static boolean isMediaDocument(Uri uri) {
		return "com.android.providers.media.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is Google Photos.
	 */
	public static boolean isGooglePhotosUri(Uri uri) {
		return "com.google.android.apps.photos.content".equals(uri.getAuthority());
	}

}
